package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.PreparedStatement;

public abstract class DBManager {
	/**
	 * 加载驱动
	 */
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建连接对象
	 */
	public Connection openConnection() throws SQLException{
		String url="jdbc:mysql://localhost:3306/test";
		return DriverManager.getConnection(url, "root", "123456");
	}
	
	/**
	 * 关闭连接
	 * @return
	 */
	public void closeConnecton(Connection conn)throws SQLException{
		if(conn!=null && !conn.isClosed()){
			conn.close();
		}
	}
	
	/**
	 * 执行查询命令
	 */
	public ResultSet query(Connection conn,String sql,Object...obs)throws SQLException{
		ResultSet rs=null;
		if(conn!=null && !conn.isClosed()){
			PreparedStatement psment=conn.prepareStatement(sql);
			if(obs!=null){
				for (int i = 0; i < obs.length; i++) {
					psment.setObject((i+1), obs[i]);
				}
			}
			rs=psment.executeQuery();
		}
		return rs;
	}
	
	/**
	 * 执行无结果集命令
	 */
	public int update(Connection conn,String sql,Object...obs)throws SQLException{
		int rs=0;
		if(conn!=null && !conn.isClosed()){
			PreparedStatement psment=conn.prepareStatement(sql);
			if(obs!=null){
				for (int i = 0; i < obs.length; i++) {
					psment.setObject((i+1), obs[i]);
				}
			}
			rs=psment.executeUpdate();
		}
		return rs;
	}
}
